const fs = require('fs')
const path = require('path')
const unzipper = require('unzipper')
/**
 * 获取本地文件PATH
 * @param jsonPath 给一个起始路径
 */
export const getJsonFiles = (jsonPath) => {
  return new Promise((resolve) => {
    const dirPath:any = []
    const newFile = fs.statSync(jsonPath)
    if (newFile.isDirectory()) {
      const files = fs.readdirSync(jsonPath)
      files.forEach((item) => {
        const fPath = path.join(jsonPath, item)
        const stat = fs.statSync(fPath)
        if (stat.isDirectory()) {
          const data: any = {
            path: fs.readdirSync(fPath),
            dirName: item
          }
          dirPath.push(data)
        }
      })
      resolve({ dirPath })
    }
  })
}
/**
 * 获取本地文件PATH
 * @param dir 传入一个文件夹,递归获取文件夹里面所有文件以及路径
 * @returns {{dirPath: *[], jsonFiles: *[]}}
 */
export const getFilesAll = (dir) => {
  return new Promise((resolve) => {
    const dirs:string[] = []
    let size:number = 0
    const findJsonFile = (dir) => {
      fs.readdirSync(dir).forEach((item) => {
        const fPath:any = path.join(dir, item)
        const stat:any = fs.statSync(fPath)
        if (stat.isDirectory()) {
          findJsonFile(fPath)
        } else {
          dirs.push(fPath)
          size += stat.size
        }
      })
    }
    findJsonFile(dir)
    const data = {
      dirs: dirs,
      size: size
    }
    resolve(data)
  })
}
/**
 * 获取本地文件PATH
 * @param dir 传入一个文件夹,递归获取文件夹里面所有文件以及路径
 * @returns {{dirPath: *[], jsonFiles: *[]}}
 */
export const getFileList = (directory) => {
  const result:any[] = []
  // 读取目录内容
  return new Promise((resolve,reject) => {
    fs.readdir(directory, (err, files) => {
      if (err) {
        reject('Unable to scan directory: ' + err)
        return
      }
      // 遍历文件和文件夹
      files.forEach((file) => {
        const filePath = path.join(directory, file)
        const stats = fs.statSync(filePath)
        let type = 'file'
        if (stats.isDirectory()) {
          type = 'folder'
        } else {
          // 获取文件后缀名
          const extName = path.extname(file).toLowerCase()
          type = extName === '' ? 'file' : extName.slice(1) // 去掉'.'
        }
        // 获取文件大小（以字节为单位）
        const size = stats.size
        const data = {
          name: file,
          path: filePath,
          type: type,
          size: size
        }
        result.push(data)
      })
      // 打印结果或进行其他处理
      resolve(result)
    })
  })
}
/**
 * 复制文件夹
 * @param zipFilePath const zipFilePath = 'path/to/your/file.zip'
 * @param zipFilePath const extractTo = 'path/to/extract/directory'
 * // 示例用法
 */
export const openZip = (zipFilePath, outputDir) => {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    // 确保输出目录存在
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true })
    }
    let totalEntries = 0
    let processedEntries = 0
    const fileStream = fs.createReadStream(zipFilePath)
    fileStream
      .pipe(unzipper.Parse())
      .on('entry', (entry) => {
        totalEntries++
        const fileName = path.basename(entry.path)
        const outputFilePath = path.join(outputDir, fileName)
        // 如果条目是目录，则创建目录
        if (entry.type === 'Directory') {
          const dirPath = path.join(outputDir, entry.path)
          if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true })
          }
          entry.autodrain() // 排空目录条目
          return
        }
        // 处理文件条目
        const writeStream = fs.createWriteStream(outputFilePath)
        entry.pipe(writeStream)
        writeStream.on('finish', () => {
          processedEntries++
          console.log(`Processed ${processedEntries}/${totalEntries} files: ${fileName}`)
          // 所有条目处理完毕后解析完成
          if (processedEntries === totalEntries) {
            resolve('All files have been processed.')
          }
        })
        writeStream.on('error', (err) => {
          reject(`Error writing file ${fileName}: ${err.message}`)
        })
      })
      .on('error', (err) => {
        reject(`Error processing ZIP file: ${err.message}`)
      })
  })
}
